package com.hzdp.web.action.account.ajax;

import org.springframework.beans.factory.annotation.Autowired;

import com.hzdp.entity.UserAccount;
import com.hzdp.sms.bean.SmsVerifyResponse;
import com.hzdp.sms.service.SmsService;
import com.hzdp.user.service.UserAccountService;
import com.hzdp.util.IPUtil;
import com.hzdp.web.action.AjaxBaseAction;
import com.hzdp.web.action.account.AccountConstants;
import com.hzdp.web.action.util.MobileRegexValidator;
import com.hzdp.web.ops.remote.RemoteIpGetter;
import com.hzdp.web.util.CookieUtil;

public class AjaxRegisterAction extends AjaxBaseAction {

	public static final int SUCCESS = 1;
	public static final int InvalidMobile = 3;
	public static final int MobileExists = 4;
	public static final int InvalidCaptcha = 5;
	public static final int InvalidPSD = 6;
	public static final int VerifyCodeTimeout = 2;
	public static final int FAIL = 7;

	private String phone;
	private String verifyCode;
	private String p;
	private String captcha;

	public void setCaptcha(String captcha) {
		this.captcha = captcha;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	public void setVerifyCode(String verifyCode) {
		this.verifyCode = verifyCode;
	}

	public void setP(String p) {
		this.p = p;
	}

	@Autowired
	private SmsService smsService;
	@Autowired
	private UserAccountService userAccountService;

	@Override
	protected void executeJson() {
		UserAccount userAccount = new UserAccount();
		userAccount.setIp(IPUtil.toInt(RemoteIpGetter.getRemoteAddr(request)));
		userAccount.setMobile(phone);
		userAccount.setPassword(p);
		int userId = userAccountService.create(userAccount);
		if (userId > 0) {
			String token = userAccountService.login(userId, true);
			if (token != null && !token.isEmpty()) {
				CookieUtil.setRootCookie(request, response, AccountConstants.Token, token);
			}
			type = SUCCESS;
		}
	}

	@Override
	public int getType() {
		return type;
	}

	@Override
	public int getStatus() {
		return status;
	}

	@Override
	protected boolean checkParams() {
		// 手机号码校验
		if (phone == null || phone.isEmpty() || !MobileRegexValidator.valid(phone)) {
			type = InvalidMobile;
			msg = "手机号码有误";
			return false;
		}

		if (p == null || p.isEmpty() || p.length() < 6 || p.length() > 32) {
			type = InvalidPSD;
			msg = "密码不符合要求";
			return false;
		}

		if (!checkCaptcha()) {
			return false;
		}

		if (!checkVerify()) {
			return false;
		}

		UserAccount userAccount = userAccountService.findByMobile(phone);
		if (userAccount != null) {
			type = MobileExists;
			msg = "当前手机号码已注册";
			return false;
		}
		return true;
	}

	private boolean checkVerify() {
		boolean result = true;
		String remoteAddr = RemoteIpGetter.getRemoteAddr(request);
		SmsVerifyResponse verify = smsService.verify(phone, remoteAddr, verifyCode);
		switch (verify.getType()) {
		case SmsVerifyResponse.TIMEOUT:
			type = VerifyCodeTimeout;
			msg = "短信动态码已失效";
			result = false;
			break;
		case SmsVerifyResponse.IP_CHANGED:
			msg = "IP地址发生变化，请重试";
			type = FAIL;
			result = false;
			break;
		case SmsVerifyResponse.FAIL:
			msg = "动态码输入错误";
			type = FAIL;
			result = false;
			break;
		default:
			break;
		}
		return result;
	}

	private boolean checkCaptcha() {
		boolean result = true;
		String cookie = CookieUtil.getCookie(request, AccountConstants.CaptchaCookieKey);
		if (cookie == null || cookie.isEmpty()) {
			result = false;
		} else {
			String[] split = cookie.split(AccountConstants.CaptchaCookieKeySplit);
			if (split.length != 2) {
				result = false;
			} else {
				try {
					long time = Long.parseLong(split[1]);
					if (time < System.currentTimeMillis()) {
						result = false;
					} else {
						String generateToken = AccountConstants.generateToken(getUUID(), captcha, time);
						if (!generateToken.equals(cookie)) {
							result = false;
						}
					}
				} catch (Exception e) {
					result = false;
				}
			}
		}

		if (!result) {
			// 图片验证码已失效
			type = InvalidCaptcha;
			msg = "图形验证码已失效";
		}
		return result;
	}

	@Override
	public String getMsg() {
		return msg;
	}

}
